import {
  ProForm,
  ProFormCheckbox,
  ProFormDependency,
  ProFormDigit,
  ProFormSelect,
} from '@/components/Pro';
import {
  stationStructControllerGetStationStruct as getDetail,
  stationStructControllerGetStructStations as getHistory,
  stationStructControllerSaveStationStruct as save,
} from '@/services/ess/stationStruct';
import type { ProFormInstance } from '@ant_design/pro_components';
import { useIntl } from '@umijs/max';
import { Flex, Form, message, Space } from 'antd';
import React, { useEffect, useRef, useState } from 'react';
import Styles from './../index.less';

const LABEL_WIDTH = 120;

type FormProps = {
  bmu_rows?: number;
  bmu_columns?: number;
  temp_rows?: number;
  temp_columns?: number;
};

const BaseInfo: React.FC<{
  id: string;
  disableEdit?: boolean;
}> = ({ id, disableEdit }) => {
  const formRef = useRef<ProFormInstance>();
  const [bmuNums, setBmuNums] = useState<number[]>([0, 0]);
  const [tempNums, setTempNums] = useState<number[]>([0, 0]);
  const intl = useIntl();
  const request = async (stationId?: number, type?: number) => {
    const res = await getDetail({
      stationId: (stationId ?? id).toString(),
    });
    if (res.success) {
      const values: FormProps = {};

      if (!type || type === 1) {
        const bmu = res?.data?.bmu || {};
        const bmuRows = bmu.rows;
        const bmuColumns = bmu.columns;
        const bmuLocation = bmu.location;

        values['bmu_rows'] = bmuRows;
        values['bmu_columns'] = bmuColumns;
        setBmuNums([bmuRows, bmuColumns]);
        for (let i = 0; i < bmuRows; i++) {
          for (let j = 0; j < bmuColumns; j++) {
            values[`_bum_${i}_${j}`] = bmuLocation?.[i]?.[j];
          }
        }
      }

      if (!type || type === 2) {
        const temp = res?.data?.temp || {};
        const tempRows = temp.rows;
        const tempColumns = temp.columns;
        const tempLocation = temp.location;
        values['temp_rows'] = tempRows;
        values['temp_columns'] = tempColumns;
        setTempNums([tempRows, tempColumns]);
        for (let i = 0; i < tempRows; i++) {
          for (let j = 0; j < tempColumns; j++) {
            values[`_temp_${i}_${j}`] = tempLocation?.[i]?.[j];
          }
        }
      }

      formRef?.current?.setFieldsValue(values);
    }
  };

  useEffect(() => {
    request();
  }, []);

  return (
    <div className={Styles.tempCollectePoint}>
      <ProForm
        layout="horizontal"
        labelCol={{
          flex: `${LABEL_WIDTH}px`,
        }}
        submitter={{
          render: (_, doms) =>
            !disableEdit ? (
              <div style={{ paddingLeft: LABEL_WIDTH, paddingTop: 24 }}>
                <Space>{doms}</Space>
              </div>
            ) : null,
        }}
        onFinish={async (value) => {
          let isFail = false;
          const result: API.StationStructDTO = {
            bmu: {
              rows: value.bmu_rows,
              columns: value.bmu_columns,
            },
            temp: {
              rows: value.temp_rows,
              columns: value.temp_columns,
            },
            stationId: id,
          };
          const bmu_location = [];
          const flat_bmu_location: number[] = [];
          for (let i = 0; i < value.bmu_rows; i++) {
            const rowArr = [];
            for (let j = 0; j < value.bmu_columns; j++) {
              const _value = value[`_bum_${i}_${j}`] ?? null;
              rowArr.push(_value);
              if (_value > value.bmu_rows * value.bmu_columns) {
                message.error(intl.formatMessage({ id: 'global.structureLocation' }));
                isFail = true;
                break;
              }
              if (_value !== null) {
                flat_bmu_location.push(_value);
              }
            }
            bmu_location.push(rowArr);
          }
          if (isFail) {
            return;
          }
          if (flat_bmu_location.length > [...new Set(flat_bmu_location)].length) {
            message.error(intl.formatMessage({ id: 'global.clusterModule' }));
            return;
          }
          result.bmu.location = bmu_location;

          const temp_location = [];
          const flat_temp_location: number[] = [];
          for (let i = 0; i < value.temp_rows; i++) {
            const rowArr = [];
            for (let j = 0; j < value.temp_columns; j++) {
              const _value = value[`_temp_${i}_${j}`] || null;
              rowArr.push(_value);
              if (_value > value.temp_rows * value.temp_columns) {
                message.error(intl.formatMessage({ id: 'global.clusterMax' }));
                isFail = true;
                break;
              }
              if (_value !== null) {
                flat_temp_location.push(_value);
              }
            }
            temp_location.push(rowArr);
          }
          if (isFail) {
            return;
          }
          if (flat_temp_location.length > [...new Set(flat_temp_location)].length) {
            message.error(intl.formatMessage({ id: 'global.clusterModule' }));
            return;
          }
          result.temp.location = temp_location;

          const res = await save(result);
          if (res?.success) {
            message.success(intl.formatMessage({ id: 'global.editedSuccessfully' }));
          }
        }}
        formRef={formRef}
        disabled={disableEdit}
      >
        <h3 className={Styles.title}>
          {intl.formatMessage({ id: 'siteManage.schematicDiagram' })}
          <span>（{intl.formatMessage({ id: 'siteManage.schematicModule' })}）</span>
        </h3>
        {!disableEdit ? (
          <>
            <div style={{ paddingLeft: LABEL_WIDTH }}>
              <ProFormCheckbox.Group
                name="bmu_history"
                options={[
                  { label: intl.formatMessage({ id: 'siteManage.historicalInfo' }), value: '0' },
                ]}
              />
            </div>
            <ProFormDependency name={['bmu_history']}>
              {({ bmu_history }) => {
                return (
                  bmu_history?.length > 0 && (
                    <ProFormSelect
                      name="bmu_history_station"
                      label={intl.formatMessage({ id: 'siteManage.historicalPlant' })}
                      fieldProps={{
                        fieldNames: {
                          label: 'stationName',
                          value: 'id',
                        },
                      }}
                      request={async () => {
                        const res = await getHistory({
                          type: 1,
                        });
                        return res?.data || [];
                      }}
                      placeholder={intl.formatMessage({ id: 'siteManage.selectPlease' })}
                      width={200}
                      onChange={(value) => {
                        request(value, 1);
                      }}
                    />
                  )
                );
              }}
            </ProFormDependency>
          </>
        ) : null}
        <Flex gap={50}>
          <ProFormDigit
            name="bmu_rows"
            label={intl.formatMessage({ id: 'siteManage.rowwiseNumber' })}
            width={200}
            min={1}
            max={99}
            placeholder={intl.formatMessage({ id: 'siteManage.enterPlease' })}
            fieldProps={{
              onBlur: () => {
                const value = formRef?.current?.getFieldsFormatValue()?.['bmu_rows'];
                setBmuNums([value, bmuNums[1]]);
              },
            }}
          />
          <ProFormDigit
            name="bmu_columns"
            label={intl.formatMessage({ id: 'siteManage.columnNumber' })}
            width={200}
            min={1}
            max={99}
            placeholder={intl.formatMessage({ id: 'siteManage.enterPlease' })}
            fieldProps={{
              onBlur: () => {
                const value = formRef?.current?.getFieldsFormatValue()?.['bmu_columns'];
                setBmuNums([bmuNums[0], value]);
              },
            }}
            labelCol={{ span: 12 }}
          />
        </Flex>
        {bmuNums.every((num) => num > 0) ? (
          <>
            <Form.Item label={intl.formatMessage({ id: 'siteManage.locationSetting' })}>
              <span>({intl.formatMessage({ id: 'siteManage.locationSettingNumber' })})</span>
            </Form.Item>
            <div
              style={{
                maxWidth: `calc(100%  - ${LABEL_WIDTH}px - 100px)`,
                overflow: 'auto',
                marginLeft: LABEL_WIDTH,
                marginTop: -20,
              }}
            >
              {[...new Array(bmuNums[0])].map((_, rowIndex) => (
                <Flex key={rowIndex} className={Styles.editTableForm}>
                  {[...new Array(bmuNums[1] || 0)].map((_, colIndex) => (
                    <ProFormDigit
                      name={`_bum_${rowIndex}_${colIndex}`}
                      width={45}
                      placeholder=""
                      min={1}
                      max={bmuNums[0] * bmuNums[1]}
                      fieldProps={{
                        className: colIndex ? Styles.tableInput : '',
                        controls: false,
                      }}
                      key={`_bum_${rowIndex}_${colIndex}`}
                    />
                  ))}
                </Flex>
              ))}
            </div>
          </>
        ) : null}
        <h3 className={Styles.title} style={{ marginTop: 50 }}>
          {intl.formatMessage({ id: 'siteManage.diagramSetting' })}
          <span>（{intl.formatMessage({ id: 'siteManage.diagramSettingModule' })}）</span>
        </h3>
        {!disableEdit ? (
          <>
            <div style={{ paddingLeft: LABEL_WIDTH }}>
              <ProFormCheckbox.Group
                name="temp_history"
                options={[
                  { label: intl.formatMessage({ id: 'siteManage.historicalInfo' }), value: '0' },
                ]}
              />
            </div>
            <ProFormDependency name={['temp_history']}>
              {({ temp_history }) => {
                return (
                  temp_history?.length > 0 && (
                    <ProFormSelect
                      name="temp_history_station"
                      label={intl.formatMessage({ id: 'siteManage.historicalPlant' })}
                      fieldProps={{
                        fieldNames: {
                          label: 'stationName',
                          value: 'id',
                        },
                      }}
                      request={async () => {
                        const res = await getHistory({
                          type: 1,
                        });
                        return res?.data || [];
                      }}
                      placeholder={intl.formatMessage({ id: 'siteManage.selectPlease' })}
                      width={200}
                      onChange={(value) => {
                        request(value, 2);
                      }}
                    />
                  )
                );
              }}
            </ProFormDependency>
          </>
        ) : null}
        <Flex gap={50}>
          <ProFormDigit
            name="temp_rows"
            label={intl.formatMessage({ id: 'siteManage.rowwiseNumber' })}
            width={200}
            min={1}
            max={99}
            placeholder={intl.formatMessage({ id: 'siteManage.enterPlease' })}
            fieldProps={{
              onBlur: () => {
                const value = formRef?.current?.getFieldsFormatValue()?.['temp_rows'];
                setTempNums([value, tempNums[1]]);
              },
            }}
          />
          <ProFormDigit
            name="temp_columns"
            label={intl.formatMessage({ id: 'siteManage.columnNumber' })}
            width={200}
            min={1}
            max={99}
            placeholder={intl.formatMessage({ id: 'siteManage.enterPlease' })}
            fieldProps={{
              onBlur: () => {
                const value = formRef?.current?.getFieldsFormatValue()?.['temp_columns'];
                setTempNums([tempNums[0], value]);
              },
            }}
            labelCol={{ span: 12 }}
          />
        </Flex>
        {tempNums.every((num) => num > 0) ? (
          <>
            <Form.Item label={intl.formatMessage({ id: 'siteManage.locationSetting' })}>
              <span>({intl.formatMessage({ id: 'siteManage.locationSettingNumber' })})</span>
            </Form.Item>
            <div
              style={{
                maxWidth: `calc(100% - ${LABEL_WIDTH} - 100)`,
                overflow: 'auto',
                marginLeft: LABEL_WIDTH,
                marginTop: -20,
              }}
            >
              {[...new Array(tempNums[0])].map((_, rowIndex) => (
                <Flex key={rowIndex} className={Styles.editTableForm}>
                  {[...new Array(tempNums[1])].map((_, colIndex) => (
                    <ProFormDigit
                      name={`_temp_${rowIndex}_${colIndex}`}
                      width={45}
                      placeholder=""
                      min={1}
                      max={tempNums[0] * tempNums[1]}
                      fieldProps={{
                        controls: false,
                      }}
                      key={`temp_${rowIndex}_${colIndex}`}
                    />
                  ))}
                </Flex>
              ))}
            </div>
          </>
        ) : null}
      </ProForm>
    </div>
  );
};
export default BaseInfo;
